package com.css.fxfzypg.modules.maps.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.AreaBoundaryUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicDetails;
import com.css.fxfzypg.modules.SettingSeismic.repository.SettingSeismicRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SeismicInfluenceflyPbe;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.SettingSeismicInfluenceflied;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.SettingSeismicInfluencefliedRepository;
import com.css.fxfzypg.modules.maps.entity.InfluencefliedEntity;
import com.css.fxfzypg.modules.maps.entity.InfluencefliedFilesEntity;
import com.css.fxfzypg.modules.maps.queryParams.InfluencefliedQueryParams;
import com.css.fxfzypg.modules.maps.service.InfluencefliedMapService;
import com.css.fxfzypg.modules.resultupload.service.ResultTotalService;
import com.css.fxfzypg.modules.spatialData.repository.BoundaryNativeRepository;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zyt
 * @Date: 2022/11/29
 */
@Service
@Slf4j
public class InfluencefliedMapServiceImpl implements InfluencefliedMapService {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Autowired
    SysAreaService sysAreaService;

    @Resource
    SettingSeismicInfluencefliedRepository settingSeismicInfluencefliedRepository;

    @Resource
    SettingSeismicRepository settingSeismicRepository;

    @Resource
    ResultTotalService resultTotalService;

    /**
     * 数据源
     * 10.19.41.111
     */
    @Value("${spring.datasource.url}")
    private String url = "";
    @Value("${spring.datasource.username}")
    private String name = "";
    @Value("${spring.datasource.password}")
    private String pwd = "";

    /**
     * 获取数据库连接
     * SQL语句
     */
    private Connection getConnection() throws Exception {
        //Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("org.postgresql.Driver");
        Connection conn = DriverManager.getConnection(url, name, pwd);
        return conn;
    }

    /*文件查询*/
    @Override
    public List<InfluencefliedFilesEntity> getAllFile(InfluencefliedQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select * from setting_seismic_influenceflied_file ");

        StringBuilder orderSql = new StringBuilder(" order by create_time");

        StringBuilder whereSql = new StringBuilder(" where is_delete = '0'");
        //查询条件
        if (!PlatformObjectUtils.isEmpty(queryParams.getTaskId()) ){
            whereSql.append(" and task_id='" + queryParams.getTaskId() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getDetailsId()) ){
            whereSql.append(" and details_id='" + queryParams.getDetailsId() + "'");
        }

        sql.append(whereSql).append(orderSql).toString();

        //查询
        List<InfluencefliedFilesEntity> files = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedFilesEntity.class));

        return files;
    }

    /*数据模糊全查询*/
    @Override
    public Map<String,Object> getAllData(InfluencefliedQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select *,ST_AsText(geom) geomText from setting_seismic_influenceflied_import ");

        StringBuilder orderSql = new StringBuilder(" order by fileuuid");

        StringBuilder whereSql = new StringBuilder(" where isdelete = '0'");
        //查询条件
        if (!PlatformObjectUtils.isEmpty(queryParams.getUuid()) ){
            whereSql.append(" and uuid='" + queryParams.getUuid() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getTaskId()) ){
            whereSql.append(" and task_id='" + queryParams.getTaskId() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getFileuuid()) ){
            whereSql.append(" and fileuuid='" + queryParams.getFileuuid() + "'");
        }

        //int firstIndex=(queryParams.getCurPage()-1) * queryParams.getPageSize();
        //int lastIndex=queryParams.getCurPage() * queryParams.getPageSize();
        sql.append(whereSql).append(orderSql).toString();
        //StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedEntity.class)).size();
        //不分页，全部查询
        List<InfluencefliedEntity> datas = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedEntity.class));
        Map<String,Object> map=new HashMap();
        map.put("total",total);
        map.put("rows",datas);
        return map;
    }

    /*根据ID查询数据*/
    @Override
    public Map<String,Object> getDataById(String id) {
        StringBuilder sql = new StringBuilder(" select *,ST_AsText(geom) geomText from setting_seismic_influenceflied_import ");

        StringBuilder orderSql = new StringBuilder(" order by fileuuid");

        StringBuilder whereSql = new StringBuilder(" where isdelete = '0'");

        //查询条件
        if (!PlatformObjectUtils.isEmpty(id) ){
            whereSql.append(" and uuid='" + id + "'");
        }
        sql.append(whereSql).append(orderSql).toString();
        List<InfluencefliedEntity> datas = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(InfluencefliedEntity.class));
        Map<String,Object> map=new HashMap();
        map.put("rows",datas);
        return map;
    }

    /*根据任务ID逻辑删除导入影响场文件及物理删除相关数据*/
    @Override
    public void deleteFileDataByTaskId(String taskId) {
        if (!PlatformObjectUtils.isEmpty(taskId)){
            InfluencefliedQueryParams queryParams = new InfluencefliedQueryParams();
            queryParams.setTaskId(taskId);
            //导入影响场文件查询
            List<InfluencefliedFilesEntity> influencefliedFilesList = getAllFile(queryParams);
            if(influencefliedFilesList!=null && influencefliedFilesList.size()>0){
                List<String> fileuuidList = new ArrayList<String>();
                for(int i=0;i<influencefliedFilesList.size();i++){
                    fileuuidList.add(influencefliedFilesList.get(i).getUuid());
                }
                String userID = PlatformSessionContext.getUserID();
                //逻辑删除文件及物理删除相关数据
                deleteFileData(taskId,null,fileuuidList,userID);
            }
        }
    }

    /*根据任务ID和detailsId逻辑删除导入影响场文件及物理删除相关数据*/
    @Override
    public void deleteFileDataByTaskIdDetailsId(String taskId,String detailsId) {
        if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(detailsId)){
            InfluencefliedQueryParams queryParams = new InfluencefliedQueryParams();
            queryParams.setTaskId(taskId);
            queryParams.setDetailsId(detailsId);
            //导入影响场文件查询
            List<InfluencefliedFilesEntity> influencefliedFilesList = getAllFile(queryParams);
            if(influencefliedFilesList!=null && influencefliedFilesList.size()>0){
                List<String> fileuuidList = new ArrayList<String>();
                for(int i=0;i<influencefliedFilesList.size();i++){
                    fileuuidList.add(influencefliedFilesList.get(i).getUuid());
                }
                String userID = PlatformSessionContext.getUserID();
                //逻辑删除文件及物理删除相关数据
                deleteFileData(taskId,detailsId,fileuuidList,userID);
            }
        }
    }

    /*逻辑删除文件及物理删除相关数据*/
    @Override
    public void deleteFileData(String taskId,String detailsId,List<String> ids, String userId) {
        //逻辑删除文件
        deleteFile(ids, userId);
        //物理删除相关数据
        deleteData(ids);
        if(!PlatformObjectUtils.isEmpty(detailsId)){
            //物理删除相关数据--地震影响场
            deleteSsi3ByTaskId(taskId,detailsId);
            //物理删除相关数据--地震影响场全部union
            deleteSip3ByTaskId(taskId,detailsId);
        }
        //删除导入影响场标识
        updateAllImportFlag(taskId,detailsId,"0");
    }

    //逻辑删除文件
    @Transactional(rollbackFor = Exception.class)
    public void deleteFile(List<String> ids, String userId) {
        //逻辑删除文件
        String sql = "update setting_seismic_influenceflied_file set is_delete = '1' , update_time='"+ PlatformDateUtils.getCurrentTimestamp()+"', update_user = '"+userId+"' where uuid in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    //物理删除相关数据
    @Transactional(rollbackFor = Exception.class)
    public void deleteData(List<String> ids) {
        //物理删除相关数据
        String sql = "delete from setting_seismic_influenceflied_import where fileuuid in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    //物理删除相关数据--地震影响场
    @Transactional(rollbackFor = Exception.class)
    public int deleteSsi3ByTaskId(String taskId,String detailsId) {
        String sql = "delete from setting_seismic_influenceflied where data_source='3' and task_id='" + taskId + "' and source_earthquake_id='"+detailsId+"'";
        return jdbcTemplate.update(sql);
    }
    //物理删除相关数据--地震影响场全部union
    public int deleteSip3ByTaskId(String taskId,String detailsId) {
        String sql = "delete from seismic_influencefly_pbe where task_id='" + taskId + "' and details_id='"+detailsId+"'";
        return jdbcTemplate.update(sql);
    }

    //校验shp文件
    public String checkSHPFiles(String taskId,String detailsId,String filePath, String formatDate, String userID) {
        try {
            String returnMsg = "";
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            System.out.println(new Date()+"-------------------2.开始校验");
            //校验是否为2000坐标系
            if (!(checkCGCS2000(filePath))){
                System.out.println(new Date()+"-----------校验失败.请上传正确的CGCS2000坐标系数据及.prj文件.");
                return "checkNotCGCS2000";
            }
            String cpgPath = filePath.substring(0, filePath.length() - 4) + ".cpg";
            String codeType = readCPG(cpgPath);//读取cpg文件编码
           
            //读取shp文件并校验--type上传类型（导入地震影响场_）
            List<Object> list = readSHPFileCheck(filePath, codeType,"导入地震影响场_", null);
            codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
            int dataLength = (int) list.get(1);//数据长度
            String checkResult = (String) list.get(2);//校验结果
            //编码类型（0：UTF-8，1：GBK）
            if (codeType.equals("UTF-8")) {
                codeType = "0";
            }else{
                codeType = "1";
            }
            System.out.println(new Date()+"-------------------3.结束readSHPFile");
            System.out.println(new Date()+"-----------4.结束校验");
            if(checkResult.equals("校验成功")){
                System.out.println(new Date()+"-------------------1.完成校验GeometryIsNotEqualsCoordinate");
                System.out.println(new Date()+"-------------------2.完成校验是否有乱码");
                System.out.println(new Date()+"-------------------3.完成校验字段空值");
                //System.out.println(new Date()+"-------------------4.完成校验是否为罗马数字");
                System.out.println(new Date()+"-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                //上传文件信息
                InfluencefliedFilesEntity influencefliedFilesEntity = new InfluencefliedFilesEntity();
                influencefliedFilesEntity.setUuid(UUIDGenerator.getUUID());
                influencefliedFilesEntity.setFilepath(filePath);
                influencefliedFilesEntity.setTaskId(taskId);//预评估任务ID
                influencefliedFilesEntity.setDetailsId(detailsId);//setting_seismic_details明细表id
                influencefliedFilesEntity.setAffiliatedFileName(fileName);
                influencefliedFilesEntity.setDateStr(formatDate);
                influencefliedFilesEntity.setIsSave("0");
                influencefliedFilesEntity.setIsDelete("0");
                influencefliedFilesEntity.setPostfix("shp");
                influencefliedFilesEntity.setQualityStatus("1");//上传省市级类型（0：省，1：市）
                influencefliedFilesEntity.setCodeType(codeType);//编码类型（0：UTF-8，1：GBK）
                influencefliedFilesEntity.setDataLength(dataLength);//数据长度
                influencefliedFilesEntity.setCreateUser(userID);//登录人
                System.out.println(new Date()+"-------------------4.开始保存");
                //保存到上传文件管理表
                saveMapFiles(influencefliedFilesEntity);
                //根据类型保存到数据库
                returnMsg = saveQhMapFilesToDatabaseByType(influencefliedFilesEntity);
                System.out.println(new Date()+"-------------------5.结束保存");
            }else{
                System.out.println(new Date()+"-----------校验失败."+checkResult);
                returnMsg = "上传文件中第"+(dataLength+1)+"行数据#" + checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //根据类型保存到数据库
    public String saveQhMapFilesToDatabaseByType(InfluencefliedFilesEntity influencefliedFilesEntity) {
        String fileUuid = influencefliedFilesEntity.getUuid();
        String taskId = influencefliedFilesEntity.getTaskId();
        String detailsId = influencefliedFilesEntity.getDetailsId();//setting_seismic_details明细表id
        String filePath = influencefliedFilesEntity.getFilepath();
        String affiliatedFileName = influencefliedFilesEntity.getAffiliatedFileName();
        //String createUser  = influencefliedFilesEntity.getCreateUser();
        String postfix = influencefliedFilesEntity.getPostfix();//文件类型：shp | gdb
        String codeType = influencefliedFilesEntity.getCodeType();//编码类型（0：UTF-8，1：GBK）
        int dataLength = influencefliedFilesEntity.getDataLength();
        String createUser = influencefliedFilesEntity.getCreateUser();//创建人
        String dateStr = influencefliedFilesEntity.getDateStr();//日期
        if(codeType.equals("0")){
            codeType = "UTF-8";
        }else{
            codeType = "GBK";
        }
        System.out.println(new Date()+"------开始导入."+affiliatedFileName+"----数据长度."+dataLength);
        //test
        /*if(dataLength>1000000){
            return "导入失败."+affiliatedFileName+"数据长度过大"+dataLength;
        }*/
        String resMsg = affiliatedFileName;//返回结果
        String result = "";
        try{
            //更新为正在保存状态
            updateSaveNowQhMapFile(influencefliedFilesEntity);
            //查询文件
            InfluencefliedQueryParams queryParams = new InfluencefliedQueryParams();
            queryParams.setTaskId(taskId);
            List<InfluencefliedFilesEntity> list = getAllFile(queryParams);
            //上传日期的所有文件数量
            int fileListCount = 0;
            if(list!=null){
                fileListCount = list.size();
            }
            //保存
            if(postfix.equals("shp")){//保存shp文件
                result = newImportShapeFile(taskId,detailsId,filePath,fileUuid,codeType,dataLength);
            }else if(postfix.equals("gdb")){//保存GDB文件
                //result = this.qhProbabilityEarthquakeDangerService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
            }
            //已保存成功
            if(result.contains("成功导入")){
                /*if(list!=null && list.size()>0){
                    //批量更新为已删除状态
                    updateLogicDeleteQhMapFiles(list);
                }*/
                //更新为已保存状态
                updateSaveQhMapFile(influencefliedFilesEntity);
                resMsg += "导入成功." + result + "当前数据所在文件UUID"+fileUuid;
            }else{
                resMsg += "导入失败." + result;
            }
        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return resMsg;
    }

    //保存shp文件数据
    public String newImportShapeFile(String taskId,String detailsId, String filePath, String fileUuid, String codeType, int dataLength) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            System.out.println(new Date()+"-------------------1.开始保存");
            //保存--zyt
            int count = newSaveData(taskId, filePath, codeType, dataLength, fileUuid);
            if(count==dataLength){
                System.out.println(new Date()+"-------------------2.结束保存");
                //保存地震影响场--保存数据union
                newSaveDataUnion(taskId,detailsId);
                returnMsg.append("成功导入" + count + "条数据.");
            }else{
                System.out.println(new Date()+"-------------------2.结束保存");
                returnMsg.append("导入出现异常，仅导入" + count + "条数据.");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存shp文件数据
    private int newSaveData(String taskId, String filePath, String codeType, int dataLength, String fileUuid) {
        int count = 0;
        int num = 5000;//每次保存的数据长度
        Connection conn = null;
        try {
            conn = getConnection();
            String prjPath = filePath.substring(0, filePath.length() - 4) + ".prj";
            String strWKTMercator = readPRJ(prjPath);
            if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
            System.out.println(new Date()+"-------------------1.开始readSHPFile");
            SimpleFeatureCollection colls = readShp(filePath, null, codeType);
            System.out.println(new Date()+"-------------------2.结束readSHPFile");
            //新增
            String tempsql = "insert into setting_seismic_influenceflied_import (" +
                "uuid,pga,pgv,pgv_vs30,intensity,task_id,fileuuid," +
                "geom) values ";

            StringBuffer sql = new StringBuffer("");
            int total = dataLength;
            boolean bool = false;//是否保存
            //开始时间
            Long begin = new Date().getTime();
            String lonLatStr = "", wkt = "";
            SimpleFeatureIterator iters = colls.features();
            while (iters.hasNext()) {
                SimpleFeature sf = iters.next();
                List<Object> values = sf.getAttributes();

                //空间数据
                String geo = values.get(0).toString();
                String geom = null;
                if (geo != null) {
                    geom = "ST_GeometryFromText('" + geo + "',4490)";
                }
                //创建人ID
                //createUser = (createUser != null ? createUser : "");
                //Timestamp createTime = PlatformDateUtils.getCurrentTimestamp();

                //主键
                String uuid = UUIDGenerator.getUUID();
                int i = 1;
                //PGA
                String pga = values.get(i++).toString();
                if (PlatformObjectUtils.isEmpty(pga)){
                    pga = null;
                }
                //PGV
                String pgv = values.get(i++).toString();
                if (PlatformObjectUtils.isEmpty(pgv)){
                    pgv = null;
                }
                //PGV_vs30
                String pgv_vs30 = values.get(i++).toString();
                if (PlatformObjectUtils.isEmpty(pgv_vs30)){
                    pgv_vs30 = null;
                }
                //intensity
                String intensity = values.get(i++).toString();

                //获取烈度值
                String dzIntensityStr = getDzIntensity(intensity);
                if(!PlatformObjectUtils.isEmpty(dzIntensityStr)){
                    int dzIntensity = Integer.parseInt(dzIntensityStr);
                    //只导入6-10烈度的数据
                    if(dzIntensity>=6 && dzIntensity<=10){
                        count++;
                        bool = false;//是否保存
                        if(count<total){
                            if(count % num == 0){
                                bool = true;//是否保存
                                //开始时间
                                begin = new Date().getTime();
                            }
                        }else{
                            bool = true;//是否保存
                        }
                        sql.append("('" + uuid
                                + "'," + pga + "," + pgv + "," + pgv_vs30 + ",'" + intensity
                                + "','" + taskId + "','" + fileUuid
                                + "'," + geom +"),");

                        if(bool){
                            String sql_str = tempsql + sql.toString();
                            sql_str = sql_str.substring(0, sql_str.length() - 1);
                            PreparedStatement ps = conn.prepareStatement(sql_str);
                            //ps.executeUpdate(sql_str);
                            ps.executeUpdate();
                            if (ps != null) ps.close();
                            //结束时间
                            Long end = new Date().getTime();
                            //耗时
                            System.out.println(new Date()+"----count: " + count+",cast : " + (end - begin) / 1000 + " s");
                            //清空
                            sql.setLength(0);
                        }
                    }
                }
            }
            iters.close();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("保存第" + count + "条数据出现异常!");
            //已保存的数量
            count = (int) Math.floor(count / num) * num;
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return count;
    }

    //保存地震影响场--保存数据union
    private int newSaveDataUnion(String taskId,String detailsId) {
        int count = 0;
        List<String> resultList = new ArrayList<String>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取明细
            SettingSeismicDetails settingSeismicDetails = settingSeismicRepository.getSettingSeismicDetailsById(detailsId);
            System.out.println(new Date()+"-------------------1.开始union");
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String influenceflyId = null;
            if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(settingSeismicDetails.getId())) {
                conn = getConnection();
                String selectSql = "select intensity,st_astext(st_union(geom)) as geom from setting_seismic_influenceflied_import" +
                        " where task_id='"+taskId+"' GROUP BY intensity";
                ps = conn.prepareStatement(selectSql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    //获取烈度值
                    String dzIntensity = getDzIntensity(rs.getString("intensity"));
                    if (!PlatformObjectUtils.isEmpty(dzIntensity)){
                        SettingSeismicInfluenceflied influenceflied = new SettingSeismicInfluenceflied();
                        String uuid = UUIDGenerator.getUUID();
                        influenceflied.setUuid(uuid);
                        influenceflied.setDzIntensity(dzIntensity);//烈度
                        influenceflied.setGeom(rs.getString("geom"));//空间数据
                        influenceflied.setDataSource("3");//数据来源：3：格网导入
                        influenceflied.setTaskId(taskId);
                        influenceflied.setAssessmentUserId(userId);
                        influenceflied.setAssessmentUserDept(sUser.getOrgId());
                        influenceflied.setAssessmentTime(PlatformDateUtils.getCurrentTimestamp());
                        influenceflied.setEarthquakeLevel(settingSeismicDetails.getEarthquakeLevel());
                        influenceflied.setSourceEarthquakeId(settingSeismicDetails.getId());
                        settingSeismicInfluencefliedRepository.saveSettingSeismicInfluenceflied(influenceflied);
                        count++;
                        if(dzIntensity.equals("6")){
                            influenceflyId = uuid;
                        }
                    }
                }
                if (!PlatformObjectUtils.isEmpty(influenceflyId)){
                    //保存地震影响场--保存数据全部union
                    newSaveDataAllUnion(taskId,detailsId,influenceflyId);
                }
                List<SettingSeismicDetails> list = new ArrayList<>();
                //更新导入影响场标识
                updateImportFlag(taskId, detailsId, "1");
                //存储每个点最外圈的地震影响场的点详情的数据
                list.add(settingSeismicDetails);
                resultTotalService.saveYpgResultNew(taskId, detailsId, list);
            }
            System.out.println(new Date()+"-------------------2.结束union，导入地震影响场结果共union"+count+"条数据");
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return count;
    }

    //保存地震影响场--保存数据全部union
    private int newSaveDataAllUnion(String taskId,String detailsId,String influenceflyId) {
        int count = 0;
        List<String> resultList = new ArrayList<String>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            System.out.println(new Date()+"-------------------1.开始全部union");
            if (!PlatformObjectUtils.isEmpty(taskId) && !PlatformObjectUtils.isEmpty(detailsId) && !PlatformObjectUtils.isEmpty(influenceflyId)) {
                //获取明细
                SettingSeismicDetails settingSeismicDetails = settingSeismicRepository.getSettingSeismicDetailsById(detailsId);

                conn = getConnection();
                String selectSql = "select st_astext(st_union(geom)) as geom from setting_seismic_influenceflied_import" +
                        " where task_id='"+taskId+"'";
                ps = conn.prepareStatement(selectSql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    SeismicInfluenceflyPbe seismicInfluenceflyPbe = new SeismicInfluenceflyPbe();
                    seismicInfluenceflyPbe.setUuid(UUIDGenerator.getUUID());
                    seismicInfluenceflyPbe.setDetailsId(settingSeismicDetails.getId());
                    seismicInfluenceflyPbe.setInfluenceflyId(influenceflyId);
                    seismicInfluenceflyPbe.setGeom(rs.getString("geom"));
                    seismicInfluenceflyPbe.setTaskId(taskId);
                    settingSeismicInfluencefliedRepository.saveSeismicInfluenceflyPbe(seismicInfluenceflyPbe);
                }
            }
            System.out.println(new Date()+"-------------------2.结束全部union");
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return count;
    }

    @Override
    public int updateImportFlag(String taskId, String detailsId, String importFlag) {
        //importFlag导入影响场标识：0未上传（包括上传后删除的） 1已上传
        String sql = "update setting_seismic_details as a set import_flag='"+importFlag+"'" +
                " from setting_seismic_point as b  where a.ss_id=b.ss_id" +
                " and a.id='" + detailsId + "' and b.task_id= '" + taskId + "'";
        int i = jdbcTemplate.update(sql);
        return i;
    }

    @Override
    public int updateAllImportFlag(String taskId, String detailsId,String importFlag) {
        //importFlag导入影响场标识：0未上传（包括上传后删除的） 1已上传
        String sql = "update setting_seismic_details as a set import_flag='"+importFlag+"'" +
                " from setting_seismic_point as b  where a.ss_id=b.ss_id" +
                " and b.task_id= '" + taskId + "'";
        if(!PlatformObjectUtils.isEmpty(detailsId)){
            sql += " and a.id='"+detailsId+"'";
        }
        int i = jdbcTemplate.update(sql);
        return i;
    }

    @Override
    public int countAllImportFlag(String taskId) {
        int count = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(taskId)) {
                conn = getConnection();
                //importFlag导入影响场标识：0未上传（包括上传后删除的） 1已上传
                String sql = "select count(*) from setting_seismic_details " +
                        "where ss_id in (select ss_id from setting_seismic_point where " +
                        "task_id= '"+taskId+"') and import_flag='1' and is_delete='0'";
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    count = Integer.parseInt(rs.getString("count"));
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return count;
    }

    //获取导入地震影响场总面积（平方米）
    @Override
    public String getSeismicInfluenceflyPbeArea(String influenceflyId) {
        String area = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (!PlatformObjectUtils.isEmpty(influenceflyId)) {
                conn = getConnection();
                String selectSql = "SELECT ST_Area(st_transform(geom,4527)) as area FROM seismic_influencefly_pbe " +
                        "WHERE influencefly_id='"+influenceflyId+"'";
                ps = conn.prepareStatement(selectSql);
                rs = ps.executeQuery();
                while (rs.next()) {
                    area = rs.getString("area");
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return area;
    }

    //获取烈度值
    public String getDzIntensity(String intensity){
        String dzIntensity = null;
        if (!PlatformObjectUtils.isEmpty(intensity) ){
            String roman = "Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ";
            String[] romanArr = roman.split(" ");
            for(int i=0;i<romanArr.length;i++){
                if(romanArr[i].equals(intensity)){
                    dzIntensity = String.valueOf(i+1);
                    break;
                }
            }
        }

        return dzIntensity;
    }

    //更新为正在保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveNowQhMapFile(InfluencefliedFilesEntity influencefliedFilesEntity) throws Exception {
        List<InfluencefliedFilesEntity> list = new ArrayList<InfluencefliedFilesEntity>();
        list.add(influencefliedFilesEntity);
        int count = 0;

        //获取数据库连接
        Connection conn = getConnection();

        String tableName = "setting_seismic_influenceflied_file";

        StringBuffer sql = new StringBuffer("UPDATE " + tableName + " set is_save = '2',update_user='" + PlatformSessionUtils.getUserId() + "',update_time='" + PlatformDateUtils.getCurrentTimestamp() + "' WHERE uuid IN ( ");
        //上传文件信息数据
        for (InfluencefliedFilesEntity entity : list) {
            count++;
            String id = entity.getUuid();
            sql.append("'" + id + "',");
        }
        String sql_str = sql.toString().substring(0, sql.length() - 1) + " )";
        PreparedStatement ps = conn.prepareStatement(sql_str);
        //ps.executeUpdate(sql_str);
        ps.executeUpdate();
        try {
            if (ps != null) {
                // 关闭连接
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return count;
    }

    //批量更新为已删除状态
    @Transactional(rollbackFor = Exception.class)
    public int updateLogicDeleteQhMapFiles(List<InfluencefliedFilesEntity> list) throws Exception {
        int count = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();

            String tableName = "setting_seismic_influenceflied_file";

            StringBuffer sql = new StringBuffer("UPDATE " + tableName + " set is_delete = '1',update_user='" + PlatformSessionUtils.getUserId() + "',update_time='" + PlatformDateUtils.getCurrentTimestamp() + "' WHERE uuid IN ( ");
            //上传文件信息数据
            for (InfluencefliedFilesEntity entity : list) {
                count++;
                String id = entity.getUuid();
                sql.append("'" + id + "',");
            }
            String sql_str = sql.toString().substring(0, sql.length() - 1) + " )";
            ps = conn.prepareStatement(sql_str);
            //ps.executeUpdate(sql_str);
            ps.executeUpdate();

        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            try {
                if (ps != null) {
                    // 关闭连接
                    ps.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return count;
    }

    //更新为已保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveQhMapFile(InfluencefliedFilesEntity influencefliedFilesEntity) throws Exception {
        List<InfluencefliedFilesEntity> list = new ArrayList<InfluencefliedFilesEntity>();
        list.add(influencefliedFilesEntity);
        int count = 0;

        /**
         * 获取数据库连接
         */
        Connection conn = getConnection();

        String tableName = "setting_seismic_influenceflied_file";

        StringBuffer sql = new StringBuffer("UPDATE " + tableName + " set is_save = '1',update_user='" + PlatformSessionUtils.getUserId() + "',update_time='" + PlatformDateUtils.getCurrentTimestamp() + "' WHERE uuid IN ( ");
        //上传文件信息数据
        for (InfluencefliedFilesEntity entity : list) {
            count++;
            String id = entity.getUuid();
            sql.append("'" + id + "',");
        }
        String sql_str = sql.toString().substring(0, sql.length() - 1) + " )";
        PreparedStatement ps = conn.prepareStatement(sql_str);
        //ps.executeUpdate(sql_str);
        ps.executeUpdate();
        try {
            if (ps != null) {
                // 关闭连接
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return count;
    }

    //校验是否为2000坐标系
    public boolean checkCGCS2000(String path) {
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator == "") return false;
        CoordinateReferenceSystem sourceTarget = null;
        try {
            sourceTarget = CRS.parseWKT(strWKTMercator);
        } catch (FactoryException e) {
            e.printStackTrace();
            System.out.println(path + ": 解析错误!");
        }
        String name = sourceTarget.getName().toString();
        if (name.equals("GCS_China_Geodetic_Coordinate_System_2000")) return true;
        return false;
    }

    //保存到上传文件管理表
    private void saveMapFiles(InfluencefliedFilesEntity influencefliedFilesEntity) throws Exception {
        Connection conn = getConnection();
        //上传文件信息表
        String tableName = "setting_seismic_influenceflied_file";
        StringBuffer sql = new StringBuffer("insert into " + tableName + " (uuid, filepath, task_id, affiliated_file_name, date_str, postfix, is_save, quality_status, is_delete, create_user, create_time, code_type,data_length,details_id) "
                + "values ");
        //上传文件信息数据
        String id = influencefliedFilesEntity.getUuid();
        String filepath = influencefliedFilesEntity.getFilepath();
        String taskId = influencefliedFilesEntity.getTaskId();
        String affiliatedFileName = influencefliedFilesEntity.getAffiliatedFileName();
        String dateStr = influencefliedFilesEntity.getDateStr();
        String postfix = influencefliedFilesEntity.getPostfix();//文件类型
        String isSave = influencefliedFilesEntity.getIsSave();//是否保存（0：未保存，1：已保存）
        String qualityStatus = influencefliedFilesEntity.getQualityStatus();//上传省市级类型（0：省，1：市）
        String isDelete = influencefliedFilesEntity.getIsDelete();//是否删除（0：未删除，1：已删除）
        String createUser = influencefliedFilesEntity.getCreateUser();
        createUser = (createUser != null ? createUser : "");
        Timestamp createTime = PlatformDateUtils.getCurrentTimestamp();
        String codeType = influencefliedFilesEntity.getCodeType();//编码类型（0：UTF-8，1：GBK）
        int dataLength = influencefliedFilesEntity.getDataLength();//数据长度
        String detailsId = influencefliedFilesEntity.getDetailsId();

        sql.append("('" + id + "','" + filepath + "','" + taskId
                +"','" + affiliatedFileName + "','" + dateStr + "','" + postfix + "','" + isSave + "','" + qualityStatus
                + "','" + isDelete + "','" + createUser + "','" + createTime +
                "','" + codeType + "'," + dataLength + ",'"+detailsId+"'),");
        String sql_str = sql.toString();
        sql_str = sql_str.substring(0, sql_str.length() - 1);
        PreparedStatement ps = conn.prepareStatement(sql_str);
        //ps.executeUpdate(sql_str);
        ps.executeUpdate();
        if (ps != null) ps.close();
        if (conn != null) conn.close();
    }

    @Autowired
    private BoundaryNativeRepository boundaryNativeRepository;
    //获取省市县所在区域字符串
    public String getDistrictBoundaryCoordinate(String province, String city, String area){
        String coordinate = "";
        return coordinate;
        /*BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setType("1");//1: 行政区划 2: 普查区划
        if(PlatformObjectUtils.isEmpty(area)){//市
            queryParams.setLevel("1");//0: 省 1: 市 2: 县
            queryParams.setName(city);
        }else{//县
            queryParams.setLevel("2");//0: 省 1: 市 2: 县
            queryParams.setName(area);
        }
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        //查询省市县所在区域边界列表
        List<BoundaryEntity> boundaryEntities = this.boundaryNativeRepository.newListBoundaries(queryParams);
        if (boundaryEntities.size() == 1) {
            BoundaryEntity boundaryEntity = boundaryEntities.get(0);
            coordinate = boundaryEntity.getCoordinate();

        } else if (boundaryEntities.size() == 0) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            System.out.println("DistrictBoundaryDataRedundance");
        }
        return coordinate;*/
    }

    //读取shp文件并校验--type上传类型（导入地震影响场_）
    public List<Object> readSHPFileCheck(String path, String codeType,String type, String boundariesCoordinate) {
        List<Object> result = new ArrayList<Object>();
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
        String lonLatStr = "", wkt = "";
        SimpleFeatureCollection colls1 = readShp(path, null, codeType);
        SimpleFeatureIterator iters = colls1.features();
        String resMsg = "校验成功";
        int count = 0;
        //校验空间分辨率不是6秒
        double lon = 0, lat = 0;
        //List<String> allWktStrList = new ArrayList<String>();//全部空间信息字符串列表
        List<Double> allLonList = new ArrayList<Double>();
        List<Double> allLatList = new ArrayList<Double>();
        SimpleFeature sf = null;

        //校验矢量面是否在省市县所在区域内
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList = new ArrayList<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>>();
        List<Geometry> multiPolygonGeometryList = new ArrayList<Geometry>();
        //Geometry boundariesGeometry = null;//行政区域
        //boundariesGeometry = getPolygonGeometryList(boundariesCoordinate);//行政区域
        //List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = getDistrictBoundaryByString(boundariesCoordinate);

        while (iters.hasNext()) {
            if(count%100000==0 && count>0){
                System.out.println(count);
            }
            sf = iters.next();
            List<Object> attributes = sf.getAttributes();
            //0.判断字段数量是否符合要求
            int size = attributes.size();
            if("导入地震影响场_".equals(type)){
                if(size<5){
                    resMsg = "fieldNumError";
                    break;
                }
            }
            //校验矢量面是否在省市县所在区域内
            /*if("RLMPolygon_".equals(type)){
                //根据属性获取矢量面列表
                List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = getPolygonList(attributes);
                //校验数据是否在省市县所在区域边界内
                if(!newCheckPointIsInDistrict(boundaries, polygonList)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }

                //添加到面经纬度列表用于校验面是否相交
                multiPolygonList.add(polygonList);
                //test
                Geometry polygon = getPolygonGeometryList(attributes.get(0).toString());
                multiPolygonGeometryList.add(polygon);
            }*/
            if("导入地震影响场_".equals(type)){
                //1.校验GeometryIsNotEqualsCoordinate
                String pointWkt = attributes.get(0).toString();
                /*String A = attributes.get(1).toString();//经度
                String B = attributes.get(2).toString();//纬度
                //新校验经纬度方法
                if (!newGeometryIsEqualsCoordinate(pointWkt, A, B)) {
                    resMsg = "GeometryIsNotEqualsCoordinate";
                    break;
                }*/

                /*//可注释判断以下判断点是否在行政区划内代码
                //判断点是否在行政区划内
                if(!newCheckPointIsInDistrictBoundary(boundaries,A,B)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }*/
            }
            //2.校验是否有乱码
            int msssyIndex = -1;
            //校验是否有乱码
            for (int j = 0; j < attributes.size(); j++) {
                if(attributes.get(j)==null){
                    continue;
                }
                String value = attributes.get(j).toString();
                for (int k = 0; k < value.length() / 2; k++) {
                    char c = value.charAt(k);
                    // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
                    //从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
                    if ((int) c == 0xfffd) {
                        // 存在乱码
                        msssyIndex = count;
                        break;
                    }
                }
                if(msssyIndex!=-1){
                    resMsg = "messyCode";
                    break;
                }
            }
            if(msssyIndex!=-1){
                break;
            }
            //3.校验字段空值
            for (int j = 0; j < attributes.size(); j++) {
                //非必填
                if(j>=1 && j<=3){
                    continue;
                }
                if(attributes.get(j)==null){
                    resMsg = "fieldNullValue";
                    break;
                }
                String value = attributes.get(j).toString();
                //校验字段空值
                if (value == null || "".equals(value.trim())){
                    resMsg = "fieldNullValue";
                    break;
                }
            }
            if(!resMsg.equals("校验成功")){
                break;
            }
            //上传类型（导入地震影响场_）
            /*if ("导入地震影响场_".equals(type)) {
                //4.校验空间分辨率不是6秒
                String A = attributes.get(1).toString();
                String B = attributes.get(2).toString();
                lon = Double.parseDouble(A);
                lat = Double.parseDouble(B);
                allLonList.add(lon);
                allLatList.add(lat);
                //校验是否空间位置重叠
                //allWktStrList.add(attributes.get(0).toString());
            }*/

            //4.校验数据内容是否符合规范
            //校验PGA
            if(!PlatformObjectUtils.isEmpty(attributes.get(1))){
                String pga = attributes.get(1).toString();
                if(!isNumericFloat(pga)){//判断字符串是否为整数或者小数
                    resMsg = "pgaFormatError";
                    break;
                }
            }
            //校验PGV
            if(!PlatformObjectUtils.isEmpty(attributes.get(2))){
                String pgv = attributes.get(2).toString();
                if(!isNumericFloat(pgv)){//判断字符串是否为整数或者小数
                    resMsg = "pgvFormatError";
                    break;
                }
            }
            //校验PGV_vs30
            if(!PlatformObjectUtils.isEmpty(attributes.get(3))){
                String pgv_vs30 = attributes.get(3).toString();
                if(!isNumericFloat(pgv_vs30)){//判断字符串是否为整数或者小数
                    resMsg = "pgv_vs30FormatError";
                    break;
                }
            }
            //校验intensity
            String intensity = attributes.get(4).toString();
            String roman = "Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ";
            if (roman.indexOf(intensity) == -1){
                resMsg = "intensityFormatError";
                break;
            }

            //获取烈度值
            String dzIntensityStr = getDzIntensity(intensity);
            if(!PlatformObjectUtils.isEmpty(dzIntensityStr)){
                int dzIntensity = Integer.parseInt(dzIntensityStr);
                //只导入6-10烈度的数据
                if(dzIntensity>=6 && dzIntensity<=10){
                    count++;
                }
            }
        }
        iters.close();
        System.out.println(count);
        if(count==0){//文件中无烈度6-10（Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ）的数据
            resMsg = "intensityNumError";
        }

        //返回结果
        result.add(codeType);//编码类型（0：UTF-8，1：GBK）
        result.add(count);//数据长度
        result.add(resMsg);//校验结果
        //校验是否有乱码
        if(resMsg.indexOf("messyCode")!=-1 && !codeType.equals("GBK")){
            result = readSHPFileCheck(path, "GBK",type, boundariesCoordinate);
        }

        return result;
    }

    //读取cpg文件编码
    public String readCPG(String path) {
        String codeType = "UTF-8";
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
            //返回结果
            codeType = result.toString();
            codeType = codeType.toUpperCase();//转换大写
        } catch (IOException e) {
            e.printStackTrace();
        }
        return codeType;
    }

    public String readPRJ(String path) {
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public SimpleFeatureCollection readShp(String path, Filter filter, String codeType) {
        SimpleFeatureSource featureSource = readStoreByShp(path, codeType);
        if (featureSource == null) return null;
        try {
            return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SimpleFeatureSource readStoreByShp(String path, String codeType) {
        File file = new File(path);
        FileDataStore store;
        SimpleFeatureSource featureSource = null;
        try {
            store = FileDataStoreFinder.getDataStore(file);
            ((ShapefileDataStore) store).setCharset(Charset.forName(codeType));
            featureSource = store.getFeatureSource();
            store.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return featureSource;
    }

    //获取省市县所在区域边界列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> getDistrictBoundaryByString(String coordinate){
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = new ArrayList<>();
        if (coordinate == null || "".equals(coordinate)) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            coordinate = coordinate.substring(coordinate.indexOf("(((") + 3, coordinate.lastIndexOf(")))"));
            coordinate = coordinate.replace(")), ((", "|");
            //coordinate = coordinate.replace("), (", "#");
            coordinate = coordinate.replace("), (", "|");
            String[] coordinates = StringUtils.split(coordinate, "|");
            for (int j = 0; j < coordinates.length; j++) {
                coordinates[j] = coordinates[j].replace(", ",";");
                coordinates[j] = coordinates[j].replace(" ",",");
                String[] lonlats = StringUtils.split(coordinates[j],";");
                com.css.fxfzypg.modules.spatialData.repository.entity.Point[] points = new com.css.fxfzypg.modules.spatialData.repository.entity.Point[lonlats.length];
                for (int i = 0;i < lonlats.length;i++) {
                    String[] lonlat = StringUtils.split(lonlats[i], ",");
                    com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point();
                    point.x = Double.parseDouble(lonlat[0]);
                    point.y = Double.parseDouble(lonlat[1]);
                    points[i] = point;
                }
                boundaries.add(points);
            }
        }

        return boundaries;
    }

    public String reverseWktMultiPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(((") + 3, oldWkt.lastIndexOf(")))"));
        oldWkt = oldWkt.replace(")), ((", "|");
        oldWkt = oldWkt.replace("), (", "#");

        String wktPolygon1 = "";
        String[] polygon1 = StringUtils.split (oldWkt, "|");
        for (int i = 0; i < polygon1.length; i++) {
            if(polygon1[i].indexOf("#")!=-1){
                String[] polygon2 = StringUtils.split(polygon1[i], "#");
                for (int j = 0; j < polygon2.length; j++) {
                    String wktPolygon2 = "";
                    String[] coords = polygon2[j].split(", ");
                    for (int k = 0; k < coords.length; k++) {
                        String[] lonLat = coords[k].split(" ");
                        String lon = lonLat[1];
                        String lat = lonLat[0];
                        wktPolygon2 += lon + " " + lat + ", ";
                    }
                    wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + "), (";
                }
                wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 4) + ")), ((";
            }else{
                String wktPolygon2 = "";
                String[] coords = polygon1[i].split(", ");
                for (int k = 0; k < coords.length; k++) {
                    String[] lonLat = coords[k].split(" ");
                    String lon = lonLat[1];
                    String lat = lonLat[0];
                    wktPolygon2 += lon + " " + lat + ", ";
                }
                wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + ")), ((";
            }
        }
        wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 6);

        return "MULTIPOLYGON (((" + wktPolygon1 + ")))";
    }

    public String reverseWktPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf("))"));

        String polygonWkt = "Polygon (", coordinate = "";
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        if ("".equals(sp)) {
            coordinate = "(";
            String[] coordinates = oldWkt.split(",");
            for (int i = 0; i < coordinates.length; i++) {
                String[] coords = coordinates[i].split(" ");
                coordinate += coords[1] + " " + coords[0] + ",";
            }
            coordinate = coordinate.substring(0, coordinate.length() - 1) + ")";
            polygonWkt += coordinate + ")";
        } else {
            oldWkt = oldWkt.replace(sp, "#"); sp = "#";
            String[] coordinates = oldWkt.split(sp);
            for (int i = 0; i < coordinates.length; i++) {
                coordinate = coordinates[i];
                String _coordinates = "(";
                String[] coords = coordinate.split(","), _coords = null;
                for (int j = 0; j < coords.length; j++) {
                    _coords = coords[j].split(" ");
                    _coordinates += _coords[1] + " " + _coords[0] + ",";
                }
                _coordinates = _coordinates.substring(0, _coordinates.length() - 1) + ")";
                polygonWkt += _coordinates + ",";
            }
            polygonWkt += polygonWkt.substring(0, polygonWkt.length() - 1) + ")";
        }
        return polygonWkt;
    }

    public String reverseWktPoint(String wktPoint) {
        String oldWkt = wktPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 1, oldWkt.lastIndexOf(")"));
        String[] coords = oldWkt.split(" ");
        return "POINT (" + coords[1] + " " + coords[0] + ")";
    }

    public String reverseWktMultiPoint(String wktMultiPoint) {
        String oldWkt = wktMultiPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf(")") - 1);
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        String[] coordinates = StringUtils.split(oldWkt, sp);
        String newWkt = "MULTIPOINT ((", coordinate = "";
        String[] coords = null;
        for (int i = 0; i < coordinates.length; i++) {
            coordinate = coordinates[i];
            coords = coordinate.split(" ");
            //newWkt += "(" + coords[1] + " " + coords[0] + "),";
            newWkt += coords[1] + " " + coords[0] + ",";
        }
        newWkt = newWkt.substring(0, newWkt.length() - 1) + "))";
        return newWkt;
    }

    //根据属性获取boundary.Point数组列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> getPolygonList(List<Object> attributes) {
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray0 = null;//面点数组
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Point>> noPointList = null;//镂空的面点数组列表
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        String coordinates = attributes.get(0).toString();
        try{
            if (coordinates.indexOf("MULTIPOLYGON") != -1) {
                coordinates = coordinates.substring(coordinates.indexOf("(((") + 3, coordinates.lastIndexOf(")))"));
                if (coordinates.indexOf(")), ((") != -1) {//多个面
                    coordinates = coordinates.replace(")), ((", "|");
                    coordinates = coordinates.replace("), (", "#");
                    String[] geometries = StringUtils.split(coordinates, "|");
                    for (int j = 0; j < geometries.length; j++) {
                        String geometry = geometries[j];
                        //获取面
                        polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(geometry);
                        polygonList.add(polygon);
                    }

                }else if (coordinates.indexOf("), (") != -1) {//单个面（包括镂空的面）
                    coordinates = coordinates.replace("), (", "#");
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);

                }else{//单个面
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            //System.out.println("矢量面："+attributes.get(0).toString());
        }

        return polygonList;
    }
    
    //根据属性获取矢量面Geometry
    public Geometry getPolygonGeometryList(String coordinates) {
        Geometry geometry = null;
        try{
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geometry = reader.read(coordinates);
        }catch (Exception e){
            e.printStackTrace();
        }

        return geometry;
    }

    public boolean newGeometryIsEqualsCoordinate(String wkt, String lon, String lat) {
        String wktPart = "";
        if (wkt.toLowerCase().indexOf("multipoint") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 2, wkt.lastIndexOf(")") - 1);
        } else if (wkt.toLowerCase().indexOf("point") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 1, wkt.lastIndexOf(")"));
        }

        int det = 1 + 8;//保留8位小数判断
        String[] array = wktPart.split(" ");
        String longitude = array[0], latitude = array[1];
        String newWktLongitudeStr = newKeepDecimalDigits(longitude, det), newWktLatitudeStr = newKeepDecimalDigits(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits(lon, det), newLatitudeStr = newKeepDecimalDigits(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            return true;
        }

        //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
        if(getGeometryIsEqualsCoordinateBool(longitude, latitude, lon, lat, det)) return true;

        return false;
    }

    private String newKeepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp=det+1;
        String tempfloatPart=floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);

        boolean bool = false;//判断是否四舍五入
        int findex=0;
        String sindex="";
        if(tempfloatPart.length()>floatPart.length()){
            if(tempfloatPart.startsWith(floatPart)&&(tempfloatPart.endsWith("9") || tempfloatPart.endsWith("8") || tempfloatPart.endsWith("7") || tempfloatPart.endsWith("6") || tempfloatPart.endsWith("5"))){
                for(int i=floatPart.length()-1;i>=0;i--){
                    String subStr = floatPart.substring(i, i+1);
                    if(subStr.equals("9")){
                        continue;
                    }
                    findex=i;
                    sindex=Integer.toString(Integer.parseInt(subStr)+1);
                    break;
                }
                floatPart= floatPart.substring(0, findex)+ sindex;
                bool = true;
            }
        }

        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        if(bool && sindex.equals("")){//floatPart都是9
            newFloatStr = Integer.toString(Integer.parseInt(floatStr.substring(0, index))+1);
        }

        return newFloatStr;
    }

    //保留8位（不四舍五入）
    private String newKeepDecimalDigits2(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
    private boolean getGeometryIsEqualsCoordinateBool(String longitude, String latitude, String lon, String lat, int det){
        boolean bool = false;
        String newWktLongitudeStr = newKeepDecimalDigits2(longitude, det), newWktLatitudeStr = newKeepDecimalDigits2(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits2(lon, det), newLatitudeStr = newKeepDecimalDigits2(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) bool= true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if(tempLon<0.000001 && tempLat<0.000001){
            bool= true;
        }

        return bool;
    }

    //截取8位小数（不四舍五入）
    public String getNewDecimalDigits(String floatStr) {
        int det = 1 + 8;
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //地球半径,单位 km
    private double EARTH_RADIUS = 6378.137;

    //根据经纬度，计算两点间的距离
    public double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        s =  s * EARTH_RADIUS;
        return s;
    }

    //判断6秒距离200
    public boolean isLessSixSecondDistance(List<Double> allLonList,List<Double> allLatList) {
        for(int i=0;i<allLonList.size();i++){
            if(i>100){//只判断100个点
                break;
            }
            double lng1 = allLonList.get(i);
            double lat1 = allLatList.get(i);
            boolean bool = false;
            double minDistance = -1;//最小距离
            for(int j=0;j<allLonList.size();j++){
                if(j==i){
                    continue;
                }
                double lng2 = allLonList.get(j);
                double lat2 = allLatList.get(j);
                double distance = getDistance(lng1,lat1,lng2,lat2);
                if(minDistance==-1 || distance<minDistance){
                    minDistance = distance;
                }
                if(distance<0.25){//250米
                    bool = true;
                    break;
                }
            }
            if(bool==false){
                System.out.println("第"+i+"条数据判断6秒距离不在250米内："+minDistance+"km--minDistance");
                System.out.println("第"+i+"条数据经纬度："+lng1+","+lat1);
                return false;
            }
        }

        return true;
    }

    //校验矢量面是否在存在单要素自相交
    public String checkIsPolygonsIntersect(List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList) {
        String resultStr = "校验成功";
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon1 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> allPolygonList = null;//全部面列表
        if(multiPolygonList!=null && multiPolygonList.size()>0) {
            allPolygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
            for (int n = 0; n < multiPolygonList.size(); n++) {
                polygonList = multiPolygonList.get(n);
                for (int i = 0; i < polygonList.size(); i++) {
                    allPolygonList.add(polygonList.get(i));
                }
            }
        }
        if(allPolygonList!=null && allPolygonList.size()>0) {
            for (int i = 0; i < allPolygonList.size(); i++) {
                polygon = allPolygonList.get(i);
                //判断矢量面是否存在自相交
                if(checkIsPolygonSelfIntersect(polygon)){
                    resultStr = "isPolygonSelfIntersect";
                    String temp = "面自相交";
                    System.out.println(temp);
                    break;
                }
            }
        }

        return resultStr;
    }

    //判断矢量面是否存在自相交
    private boolean checkIsPolygonSelfIntersect(com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon){
        boolean bool = false;//不存在自相交
        int flag = 0;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> points = polygon.points;
        for(int i = 0;i < (points.size()-1);i++){ //循环开始元素
            for(int j = i + 1;j < points.size();j++){ //循环后续所有元素
                //如果相等，则重复
                if(points.get(i).x == points.get(j).x && points.get(i).y == points.get(j).y){
                    flag++; //设置标志变量为重复
                }
            }
        }
        if(flag>1){//除首尾点外存在重复的点
            bool = true;//存在自相交
        }

        return bool;
    }

    private double GLOBAL_THRESH = 1E-6;
    //校验矢量面是否在存在两两重叠或相交（或单要素自相交）
    public String checkIsPolygonGeometrysIntersect(List<Geometry> multiPolygonGeometryList) {
        String resultStr = "校验成功";
        Geometry geometry1 = null;
        Geometry geometry2 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        if(multiPolygonGeometryList!=null && multiPolygonGeometryList.size()>0) {
            for (int i = 0; i < multiPolygonGeometryList.size(); i++) {
                geometry1 = multiPolygonGeometryList.get(i);
                //Geometry geometry1IntersectGeometry1 = geometry1.intersection(geometry1);
                //判断是否存在两两重叠或相交
                for(int j=i+1;j<multiPolygonGeometryList.size();j++){
                    geometry2 = multiPolygonGeometryList.get(j);
                    //自相交
                    //Geometry geometry2IntersectGeometry2 = geometry2.intersection(geometry2);
                    //Geometry geometry1IntersectGeometry2 = geometry1IntersectGeometry1.intersection(geometry2IntersectGeometry2);
                    //double area = geometry1IntersectGeometry2.getArea();
                    //两两相交
                    Geometry geometry1IntersectGeometry2 = geometry1.intersection(geometry2);
                    double area = geometry1IntersectGeometry2.getArea();
                    if(area >= GLOBAL_THRESH){
                        resultStr = "isPolygonsIntersect";
                        String temp = "存在两两重叠或相交";
                        //temp += "，面："+geometry1.toString();
                        //temp += "相交于面："+geometry2.toString();
                        temp += "，相交面积："+area;
                        System.out.println(temp);
                        break;
                    }
                }
                if(resultStr!="校验成功"){
                    break;
                }
            }
        }

        return resultStr;
    }

    //校验矢量面数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrict(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        if(boundaries!=null && boundaries.size()>0 && polygonList!=null && polygonList.size()>0){
            for(int i=0;i<polygonList.size();i++){
                boolean bool = false;
                polygon = polygonList.get(i);
                pointArray = polygon.points;
                if(pointArray!=null && pointArray.size()>0){
                    for(int j=0;j<pointArray.size();j++){
                        point = pointArray.get(j);
                        bool = false;
                        double minDis = Double.MAX_VALUE;
                        for (int k = 0; k < boundaries.size(); k++) {
                            boundary = boundaries.get(k);
                            if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                                bool = true;
                                break;
                            } else {//判断容差距离
                                //double minDis = Double.MAX_VALUE;
                                for (int n = 0; n < boundary.length - 1; n++) {
                                    com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                                    double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                                    if (minDis > d) minDis = d;
                                }
                                if (minDis < GLOBAL_THRESH) {
                                    bool = true;
                                    break;
                                }
                            }
                        }
                        if (bool == false){
                            String temp = "矢量面上的点："+point;
                            temp+="--------不在行政区划范围内----minDis:"+minDis;
                            System.out.println(temp);
                            return false;
                        }
                    }
                }
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    //校验点数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrictBoundary(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries,String lonStr, String latStr) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point(Double.parseDouble(lonStr), Double.parseDouble(latStr));
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        boolean bool = false;
        if(boundaries!=null && boundaries.size()>0){
            for (int k = 0; k < boundaries.size(); k++) {
                boundary = boundaries.get(k);
                if (AreaBoundaryUtil.isPointInPolygon(point, boundary)){
                    bool = true;
                    break;
                } else {//判断容差距离
                    double minDis = Double.MAX_VALUE;
                    for (int n = 0; n < boundary.length - 1; n++) {
                        com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                        double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                        if (minDis > d) minDis = d;
                    }
                    if (minDis < GLOBAL_THRESH) {
                        bool = true;
                        break;
                    }
                }
            }
            if (bool == false){
                String temp = "点："+point+"--------不在行政区划范围内----";
                System.out.println(temp);
                return false;
            }
        }else{
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    private String strWKTMercator = "PROJCS[\"CGCS2000_GK_Zone_20\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",20500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",117.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";

    public void setStrWKTMercator(String wKTMercator){
        strWKTMercator = wKTMercator;
    }

    public String wkt2lonLat(String wktPolygon){
        Geometry geomtry = null;
        try {
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geomtry = reader.read(wktPolygon);
            geomtry = webMercator2lonLat(geomtry);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (geomtry != null)
            return geomtry.toString();
        else return null;
    }

    public Geometry webMercator2lonLat(Geometry geom){
        try{
            CoordinateReferenceSystem sourceTarget = CRS.parseWKT(strWKTMercator);
            CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:4490");
            MathTransform transform = CRS.findMathTransform(sourceTarget, crsTarget, true);
            //MathTransform transform = CRS.findMathTransform(sourceTarget, DefaultGeographicCRS.WGS84, true);
            return JTS.transform(geom, transform);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取重点活动ID（11位）
    public String getZdhdId(String dateStr, int fileListCount){
        String zdhdId = dateStr;
        fileListCount = fileListCount - 1;//从0开始
        if(fileListCount<10){
            zdhdId += "00" + fileListCount;
        }else if(fileListCount<100){
            zdhdId += "0" + fileListCount;
        }else if(fileListCount<1000){
            zdhdId += String.valueOf(fileListCount);
        }

        return zdhdId;
    }

    //获取流水码（5位)
    public String getTempCountNum(int count){
        count = count - 1;//从0开始
        //流水码（5位）
        String tempCountNum = "00000";
        if(count<10){
            tempCountNum = "0000" + count;
        }else if(count<100){
            tempCountNum = "000" + count;
        }else if(count<1000){
            tempCountNum = "00" + count;
        }else if(count<10000){
            tempCountNum = "0" + count;
        }else if(count<100000){
            tempCountNum = String.valueOf(count);
        }else{//超过5位
            tempCountNum = String.valueOf(count);
        }

        return tempCountNum;
    }

    //判断字符串是否为整数或者小数（大于等于0）
    public static boolean isNumericFloat(String str){
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        float temp = Float.parseFloat(str);
        if(temp>=0){
            return true;
        }else{
            return false;
        }
    }

    //判断字符串是否为整数
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
